<template>
  <div class="col-wrapper" v-loading="loading" element-loading-text="拼命加载中">
    <div class="col-tree-box">
       <el-scrollbar>
         <el-tree highlight-current 
                  check-on-click-node
                  :expand-on-click-node="false"
                  show-checkbox 
                  ref="tree" 
                  node-key="id" 
                  default-expand-all 
                  :data="treeData" 
                  :props="defaultProps"></el-tree>
      </el-scrollbar>
    </div>
    <div class="col-data-box">
    <el-row>
      <!-- 按钮区 -->
      <el-col :span="24">
        <div class="button-wrapper">
          <el-button size="mini" type="primary" round @click="dialogFormVisible=true">增加</el-button>
          <el-button size="mini" type="warning" round  @click="batchEdit(9)">停用</el-button>
          <el-button size="mini" type="success" round  @click="batchEdit(0)">启动</el-button>
          <el-button size="mini" type="danger" round  @click="batchEdit(-1)">删除</el-button>
          <el-button size="mini" type="info" round  @click="authorization()">授权</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-col :span="24">
        <div class="data-wrapper">
          <template v-if="tableData!=null">
          <el-table ref="multipleTable" :data="tableData"  tooltip-effect="dark" style="width: 100%"
      @selection-change="handleSelectionChange">
            <el-table-column type="selection" label="全选" width="40">
            </el-table-column>
             <el-table-column type="index" label="序号" :index="indexMethod">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称">
            </el-table-column>
            <el-table-column prop="roleType" label="角色类型" :formatter="formatType"> 
            </el-table-column>
             <el-table-column prop="roleState" label="状态" :formatter="formatState">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="200">
            <template slot-scope="scope">
              <!-- <el-button title="查看" size="small" icon="el-icon-search" type="primary" circle @click="handleView(scope.$index, scope.row)"></el-button> -->
              <el-button title="编辑" size="small" icon="el-icon-edit" type="success" circle @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button title="删除" size="small" icon="el-icon-delete" type="danger" circle @click="handleDel(scope.$index, scope.row)"></el-button>
            </template>
           </el-table-column> 
          </el-table>
          </template>
        </div>
      </el-col>
    </el-row>
    <!-- 底部按钮和分页 -->
    <el-row :gutter="20" v-if="dataCount" type="flex" justify="space-between" align="center" class="page-wrapper">
      <el-col :span="20">
        <div class="page-item">
          <el-pagination background  
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page.sync="listQuery.currentPage" 
          :page-sizes="pageSizes" 
          :page-size="listQuery.pageSize" 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="dataCount"/>
        </div>
      </el-col>
    </el-row>
    </div>
    
    <!-- 弹出窗口区域 -->
    <el-dialog title="角色添加" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="form">
        <el-row :gutter="5">
          <el-col :span="24">
            <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
              <el-input v-model="form.roleName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色编码" :label-width="formLabelWidth"  prop="roleCode">
               <el-input v-model="form.roleCode" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>      
           <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="roleNote">
               <el-input type="textarea" v-model="form.roleNote" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleCancel('form')">取 消</el-button>
        <el-button size="medium" type="primary" @click="insert('form')">确 定</el-button>
      </div>
    </el-dialog>

     <!-- 弹出窗口区域 -->
    <el-dialog title="角色修改" :visible.sync="editdialogForm">
        <el-form :model="oneCol" v-if="oneCol" :rules="editRules" ref="oneCol">
         <el-row :gutter="5">
          <el-col :span="24">
            <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
              <el-input v-model="oneCol.roleName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色编码" :label-width="formLabelWidth"  prop="roleCode">
               <el-input v-model="oneCol.roleCode" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>      
           <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="roleNote">
               <el-input type="textarea" v-model="oneCol.roleNote" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleCancel('oneCol')">取 消</el-button>
        <el-button size="medium" type="primary" @click="update('oneCol')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    var validateAddRoleCode = (rule, value, callback) => {
      if (!new RegExp("^[a-zA-Z0-9]+$").test(value)) {
        callback(new Error("角色编码只能包含数字和字母"));
      } else {
        //验证角色编码是否存在

        //发送角色编码校验请求
        this.postRequest("/api/role/code/addcheck", {
          roleCode: value
        })
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              callback(new Error("角色编码已存在!"));
            } else {
              callback();
            }
          })
          .catch(error => {
            //错误信息
            callback(new Error(error));
          });
      }
    };
  var validateEditRoleCode = (rule, value, callback) => {
      if (!new RegExp("^[a-zA-Z0-9]+$").test(value)) {
        callback(new Error("角色编码只能包含数字和字母"));
      } else {
        //验证角色编码是否存在

        //发送角色编码校验请求
        this.postRequest("/api/role/code/editcheck", {
          roleId: this.oneCol.roleId,
          roleCode: value
        })
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              callback(new Error("角色编码已存在!"));
            } else {
              callback();
            }
          })
          .catch(error => {
            //错误信息
            callback(new Error(error));
          });
      }
    };
    return {
      tableData: [],
      //默认数据总数
      dataCount: 100,
      pageSizes: [5, 10, 20, 30, 40],
      //查询条件
      listQuery: {
        currentPage: 1,
        pageSize: 5
      },
      listSelect: [],
      dialogFormVisible: false,
      showDialog: false,
      editdialogForm: false,
      loading: false,
      form: { roleType: "0" },
      oneCol: {},
      rules: {
        roleName: [{ required: true, message: "请输角色名称", trigger: "blur" }],
        roleCode: [{ required: true, message: "请输角色编号", trigger: "blur" },
                   {validator: validateAddRoleCode, trigger: "blur" } ],
      },
      editRules:{
        roleName: [{ required: true, message: "请输角色名称", trigger: "blur" }],
        roleCode: [{ required: true, message: "请输角色编号", trigger: "blur" },
                   {validator: validateEditRoleCode, trigger: "blur" } ],
      },
      formLabelWidth: "100px",
      defaultProps: {
        children: "children",
        label: "title"
      }
    };
  },
  created() {

  },
  mounted() {
    this.getList();
  },
  updated() {},
  destroyed() {},
  computed:{
    treeData:function(){
      return this.$store.state.menuTree
    }
  },
  methods: {
    //角色类型翻译
    formatType: function(row, column) {
      if (row.roleType == 0) {
        return "普通角色";
      } else if (row.roleType == 1) {
        return "管理员";
      } else if (row.roleType == 2) {
        return "超级管理员";
      }
    },
    // 状态翻译
    formatState: function(row, column) {
      return row.roleState == 0 ? "启用" : "停用";
    },
    //列表查询
    getList() {
      this.loading = true;
      this.getRequest("/api/roles/management", this.listQuery)
        .then(res => {
          var data = res.data;
          if (data.status == 200) {
            this.tableData = data.data;
            this.dataCount = data.count;
          } else {
            this.$message.error(data.msg);
          }
          this.loading = false;
        })
        .catch(error => {
          //错误信息
          this.$message.error(error);
        });
    },
    //搜索功能
    handSearch(val) {
      this.getList();
    },
    //新增
    insert(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.postRequest("/api/role", this.form)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.dialogFormVisible = false;
                this.getList();
                this.form = {};
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        } else {
          this.$message.error("error submit!!");
          return false;
        }
      });
    },
    //单个删除
    handleDel(index, row) {
      this.$confirm("确认删除？").then(_ => {
        this.deleteRequest("/api/role", { roleId: row.roleId })
          .then(res => {
            var data = res.data;
            this.$message.success(data.msg);
            this.getList();
          })
          .catch(error => {
            //错误信息
            this.$message.error(error);
          });
      }).catch(() => {
          this.$message.info('已取消操作');          
        });
    },
    //更新
    update(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.putRequest("/api/role", this.oneCol)
            .then(res => {
              var data = res.data;
              if (data.status == 200) {
                this.$message.success(data.msg);
                this.editdialogForm = false;
                this.getList();
                this.oneCol = {};
              } else {
                this.$message.error(data.msg);
              }
            })
            .catch(error => {
              //错误信息
              this.$message.error(error);
            });
        } else {
          this.$message.error("error submit!!");
          return false;
        }
      });
    },
    //批量编辑
    batchEdit(val) {
      if (this.listSelect.length <= 0) {
        this.$message.warning("请选择一条数据");
        return;
      }

      var strArr = [];
      for (var i = 0; i < this.listSelect.length; i++) {
        strArr.push(this.listSelect[i].roleId);
      }

      //前面三个参数分别是 表名，状态字段名，id字段名
      //status 为状态值 （0：正常  9：停用 -1：删除）
      //ids 为需要批量操作的 id数组
      var submitData = {
        tableName: "sys_role",
        tableCol: "role_state",
        tableId: "role_id",
        status: val,
        ids: strArr
      };

      this.$confirm("确认批量操作？").then(_ => {
        this.putRequest("/api/common/batch", submitData)
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              this.$message.success(data.msg);
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          })
          .catch(error => {
            //错误信息
            this.$message.error(data.msg);
          });
      }).catch(() => {
          this.$message.info('已取消操作');          
        });
    },
    handleSelectionChange(val) {
      this.listSelect = val;
    },
    indexMethod(index) {
      return index + 1 + (this.listQuery.currentPage - 1) * this.listQuery.pageSize;
    },
    //每页个数改变
    handleSizeChange(size) {
      this.listQuery.pageSize = size;
      this.listQuery.currentPage = 1;
      this.getList();
    },
    //当前页改变
    handleCurrentChange(currentPage) {
      this.listQuery.currentPage = currentPage;
      this.getList();
    },
    //角色授权
    authorization() {
      if (this.listSelect.length <= 0) {
        this.$message.warning("请选择一个角色");
        return;
      }
      if (this.listSelect.length > 1) {
        this.$message.warning("只能选择一个角色");
        return;
      }

      var checkNodes = this.$refs.tree.getCheckedNodes();

      if (checkNodes.length <= 0) {
        this.$message.warning("请选择授权菜单");
        return;
      }

      var strArr = [];
      for (var i = 0; i < checkNodes.length; i++) {
        strArr.push(checkNodes[i].value);
      }

      var submitData = {
        roleId: this.listSelect[0].roleId,
        menuIds: strArr
      };

      this.$confirm("确认授权？").then(_ => {
        this.postRequest("/api/role/authorization", submitData)
          .then(res => {
            var data = res.data;
            if (data.status == 200) {
              this.$message.success(data.msg);
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          })
          .catch(error => {
            //错误信息
            this.$message.error(error);
          });
      }).catch(() => {
          this.$message.info('已取消操作');          
        });
    },
    //显示编辑弹窗
    handleEdit(index, row) {
      this.oneCol = row;
      this.editdialogForm = true;
    },
     // 树弹窗取消
    handleCancel(formName){
      this.dialogFormVisible = false
      this.editdialogForm = false
      this.$refs[formName].resetFields();
    },
  }
};
</script>
<style scoped>
</style>
